# -*- coding: utf-8 -*-
# @Time    : 2021/5/2 17:23
# @Author  : RanyLra
# @Wechat  : RanY_Luck
# @File    : db.py
import json
from datetime import datetime
from typing import Union

import pymysql

from tools.read_file import ReadFile


class DB:
    mysql = ReadFile.read_config('$.database')

    def __init__(self):
        """初始化连接Mysql"""
        self.connection = pymysql.connect(
            host=self.mysql.get('host', 'host'),
            port=self.mysql.get('port', 'port'),
            user=self.mysql.get('user', 'user'),
            password=self.mysql.get('password', 'password'),
            db=self.mysql.get('db_name', 'db_name'),
            charset=self.mysql.get('charset', 'utf8mb4'),
            cursorclass=pymysql.cursors.DictCursor
        )

    def execute_sql(self, sql: str) -> Union[dict, None]:
        """
        执行sql语句方法，查询所有结果的sql只会返回一条结果(
        eg:使用select * from cases,结果只会返回第一条数据 {'id': 1, 'name': 'updatehahaha', 'path': None, 'body': None, 'expected': '{"msg": "你好"}', 'api_id': 1, 'create_at': '2021-05-23 17:23:54', 'update_at': '2021-05-23 17:23:54'})
        支持select，delete，insert，updata
        :param sql: sql语句
        :return: select 语句 如果有结果则会返回 对应结果字典，delete，insert，update 将返回None
        """
        with self.connection.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchone()
            # 使用commit 解决查询数据出现概率问题
            self.connection.commit()
            return self.verify(result)

    def verify(self, result: dict) -> Union[dict, None]:
        """
        验证结果是否被json.dumps序列化
        """
        # 尝试变成字符串，解决datetime 无法被JSON 序列化问题
        try:
            json.dumps(result)
        except TypeError:
            for k, v in result.items():
                if isinstance(v, datetime):
                    result[k] = str(v)

    def close(self):
        """关闭数据库连接"""
        self.connection.close()


if __name__ == '__main__':
    # print(ReadFile.read_config('$.database'))
    # DB()
    pass
